const tbody = document.querySelector("tbody");
let index;
async function getdata() {
    const res = await axios({
        url: '/student/list',
        method: "get"
    })
    tbody.innerHTML = res.data.data.reduce((prveHtml, item) => {
        const { name, id, city, county, group, phone, province, salary, sex, age, truesalary } = item
        return prveHtml + `
        <tr>
        <th scope="row">${id}</th>
        <td>${name}</td>
        <td>${age}</td>
        <td>${sex}</td>
        <td>${group}</td>
        <td>${phone}</td>
        <td>${salary}</td>
        <td>${truesalary}</td>
        <td>${province}${city}${county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm" data-id="${id}">修改</button>
          <button data-id="${id}" type="button" class="btn btn-danger btn-sm">删除</button>
        </td>
      </tr>
        `
    }, "");

};

const addstudent = document.querySelector("#addstudent");
const formModal = document.querySelector("#formModal");
const province = document.querySelector("[name=province]");
const city = document.querySelector("[name=city]");
const county = document.querySelector("[name=county]");
const form = document.querySelector("#formModal form")
const modalTitle = document.querySelector("#modalTitle");

// 添加学员
addstudent.addEventListener("click", function (e) {
    $("#formModal").modal("show");
    modalTitle.innerText = "录入新学员"
    form.reset()
    // 初始化省市县
    getData();

});
const submit = document.querySelector("[type=submit");
// 提交
submit.addEventListener("click", async function (e) {
    e.preventDefault()

    const data = serialize(document.querySelector('#formModal form'), { hash: true })

    if (modalTitle.innerText === "录入新学员") {
        const res = await axios({
            url: '/student/add',
            method: 'post',
            data
        });
        $("#formModal").modal("hide");
        getdata()

    } else if (modalTitle.innerText === "编辑学员") {
        console.log(index);
        data.id = index
        console.log(data);
        const res = await axios({
            url: '/student/update',
            method: "put",
            data
        });
        console.log(res);
        $("#formModal").modal("hide");
        getdata()
    }

})
// 编辑
tbody.addEventListener("click", async function (e) {
    index = e.target.dataset.id
    if (e.target.classList.contains('btn-primary')) {
        // console.log(e.target.dataset.id);
        modalTitle.innerText = "编辑学员"
        $("#formModal").modal("show");
        const res = await axios({
            url: '/student/one',
            params: {
                id: index
            }
        });
        const obj = res.data.data
        for (const key in obj) {
            const formEle = form.querySelector(`[name=${key}]`)
            if (formEle && key != "gender") {
                formEle.value = obj[key]
            }
        }
        const pname = res.data.data.province;
        const cname = res.data.data.city;
        await getSelectData('/geo/city', { pname }, 'city')
        await getSelectData('/geo/county', { pname, cname }, 'county')
    } else if (e.target.classList.contains('btn-danger')) {
        const res = await axios({
            url: '/student/delete',
            method: "delete",
            params: {
                id: index
            }
        });
        getdata();
    }
})


// 优化
async function getSelectData(url, params, target) {
    const res = await axios({
        url,
        params
    });
    const html = res.data.reduce((beforeHTML, item) => {
        return beforeHTML + `<option value="${item}">${item}</option>`
    }, '');
    document.querySelector(`[name=${target}]`).innerHTML = html;
}
// 获取省
async function getProvince() {
    await getSelectData('/geo/province', {}, 'province')
}
// 获取市
async function getCity() {
    const pname = document.querySelector('[name=province]').value;
    await getSelectData('/geo/city', { pname }, 'city')
}

// 获取县
async function getArea() {
    const pname = document.querySelector('[name=province]').value;
    const cname = document.querySelector('[name=city]').value;
    await getSelectData('/geo/county', { pname, cname }, 'county')
}

async function getData() {
    await getProvince();
    await getCity();
    await getArea()
}
getData()

// 点击省切换对应市
document.querySelector('[name=province]').addEventListener("change", async function (e) {
    await getCity();
    getArea()

})
// 点击市切换对应县
document.querySelector('[name=city]').addEventListener("change", async function () {
    getArea()
})
// 页面渲染
getdata()

